package cn.zjweu.servlet;

import cn.zjweu.domain.Dish;
import cn.zjweu.domain.MessageInfo;
import cn.zjweu.domain.PageBean;
import cn.zjweu.domain.ResultInfo;
import cn.zjweu.service.DishService;
import cn.zjweu.service.impl.DishServiceImpl;
import cn.zjweu.utils.BaseServlet;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/*Designed By YeJianFeng-2022b32057*/
@WebServlet("/dish/*")
public class DishServlet extends BaseServlet {

    private DishService dishService = new DishServiceImpl();

    /*查找菜品列表*/
    public void findDish(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String currentPageStr = request.getParameter("currentPage");
        String dishName = request.getParameter("dishName");
        String categoryName = request.getParameter("categoryName");
        String pageSizeStr = request.getParameter("pageSize");
        int currentPage = MessageInfo.DEFAULT_CURRENT_PAGE;
        if (currentPageStr != null && currentPageStr.length() > 0) {
            currentPage = Integer.parseInt(currentPageStr);
        }

        int pageSize = MessageInfo.DEFAULT_PAGE_SIZE;
        if (pageSizeStr != null && pageSizeStr.length() > 0) {
            pageSize = Integer.parseInt(pageSizeStr);
            if (pageSize < 1) {
                pageSize = MessageInfo.DEFAULT_PAGE_SIZE;
            }
        }

        PageBean<Dish> pageOfDish = dishService.findDishPageByDishAndCategory(currentPage, pageSize, dishName, categoryName);
        writeValue(pageOfDish, response);
    }

    /*通过菜品ID找菜品信息*/
    public void findDishById(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ResultInfo info = new ResultInfo();
        int dishId = 0;
        try {
            dishId = Integer.parseInt(request.getParameter("dishId"));
        } catch (Exception e) {
            System.out.println("菜品ID查找失败");

            info.setFlag(MessageInfo.FAIL);
            info.setData(dishId);
            info.setInfoMsg("菜品ID获取错误！");
            writeValue(info, response);
        }
        System.out.println("查找菜品ID：" + dishId);

        Dish dish = dishService.findDishById(dishId);
        if (dish == null) {
            info.setFlag(MessageInfo.FAIL);
            info.setData(dishId);
            info.setInfoMsg("菜品获取失败！");
        } else {
            info.setFlag(MessageInfo.SUCCESS);
            info.setData(dish);
            info.setInfoMsg("查找成功！");
        }

        writeValue(info, response);
    }
}
